<?php

namespace zycom\top;

defined('TOP_SDK_WORK_DIR') or define('TOP_SDK_WORK_DIR', '/tmp');
defined('TOP_SDK_DEV_MODE') or define('TOP_SDK_DEV_MODE', true);

class TopClient extends \TopClient
{
    public $authorizeUrl = 'https://oauth.taobao.com/authorize';

    public $tokenUrl = 'https://oauth.taobao.com/token';

    public $redirectUri;

    public $accessToken = '';
    public $format = 'json';

    /**
     * 设置为sandbox模式
     */
    public function setSandbox()
    {
        $this->authorizeUrl = 'https://oauth.tbsandbox.com/authorize';
        $this->tokenUrl = 'https://oauth.tbsandbox.com/token';
        $this->gatewayUrl = 'http://gw.api.tbsandbox.com/router/rest';
    }

    /**
     * 生成授权url
     *
     * @param string $redirectUri
     * @return string
     */
    public function getAuthorizeUrl($redirectUri = null)
    {
        $redirectUri || $redirectUri = $this->redirectUri;
        $param['response_type'] = 'code';
        $param['client_id'] = $this->appkey;
        $param['redirect_uri'] = $redirectUri;
        // $param['state'] = '';
        // $param['view'] = 'web';
        return $this->authorizeUrl . '?' . http_build_query($param);
    }

    /**
     * code换access_token过程封装
     *
     * @param string $code
     * @throws \Exception
     * @return mixed
     */
    public function fetchAccessToken($code)
    {
        $redirectUri = $this->redirectUri;
        $param = [
            'client_id' => $this->appkey,
            'client_secret' => $this->secretKey,
            'grant_type' => 'authorization_code',
            'code' => $code,
            'redirect_uri' => $redirectUri
        ];
        // 'state' => '',
        // 'view' => 'web'

        $json = $this->curl($this->tokenUrl, $param);
        $json = json_decode($json, true);
        $json['taobao_user_nick'] = urldecode($json['taobao_user_nick']);
        if (isset($json['sub_taobao_user_nick'])) {
            $json['sub_taobao_user_nick'] = urldecode($json['sub_taobao_user_nick']);
        } else {
            $json['sub_taobao_user_nick'] = '';
            $json['sub_taobao_user_id'] = 0;
        }
        return $json;
    }
}
